import router from '@/router'
import axios, { type AxiosInstance, type AxiosRequestConfig, type Method } from 'axios'
import { useLodingStore } from '@/stores/loding'
declare module 'axios' {
    interface AxiosRequestConfig {
        withToken?: boolean
        deepData?: boolean
        loading?: boolean
    }
}

class Http {
    private instance: AxiosInstance
    private config: AxiosRequestConfig
    constructor(options: AxiosRequestConfig) {
        this.instance = axios.create({
            timeout: options.timeout || 10000,
            // 允许在创建实例时传入更多配置
            ...options
        })
        this.init()
        this.config = {}
    }

    init() {
        this.requestInterceptor()
        this.responseInterceptor()
    }
    private handleServerError(error: number) {
        switch (error) {
            case 401:
                localStorage.removeItem('X-Auth-Token')
                router.replace('/login')
                break
            case 403:
                // 处理权限不足
                break
            case 500:
                // 处理服务器错误
                break
        }
    }
    // 请求拦截器
    private requestInterceptor() {
        this.instance.interceptors.request.use(
            (config) => {
                this.config = config
                if (config.withToken) {
                    config.headers['X-Auth-Token'] = `${localStorage.getItem('X-Auth-Token')}`
                }
                if (config.loading) {
                    useLodingStore().setLoading(true)
                }
                return config
            },
            (error) => {
                return Promise.reject(error)
            }
        )
    }

    // 响应拦截器
    private responseInterceptor() {
        this.instance.interceptors.response.use(
            (response) => {
                if (this.config.loading) {
                    useLodingStore().setLoading(false)
                }
                if (this.config.deepData) {
                    return response.data
                }
                return response
            },
            (error) => {
                this.handleServerError(error.response.status)
                return Promise.reject(error)
            }
        )
    }
    public async request<T = any>(
        method: Method,  // 使用 axios 的 Method 类型而不是 string
        url: string,
        data?: unknown,  // 使用 unknown 替代 any，更安全
        config?: AxiosRequestConfig
    ): Promise<T> {
        return this.instance.request({
            method,
            url,
            [method.toLowerCase() === 'get' ? 'params' : 'data']: data,
            ...config
        })
    }
}


export default Http

